<?php
/**
*Help func - complete node_load result for advert type.
*@param array $node - node_load result
*@return array node - completed by advert custom data result
*/
function _advert_get_node($node)
{
if($node->nid)
{
$node->advert=db_select('node_advert','na')->fields('na')->condition('nid', $node->nid)->execute()->fetchAssoc();

$public_dates_record = db_select('node_advert_dates','pd')->fields('pd')->condition('nid', $node->nid)->orderBy('public_date', 'ASC')->execute();
 while($pd = $public_dates_record->fetchAssoc()) 
 {
  
    $node->public_dates[$pd['id']]=$pd['public_date'];
 }
 
 $taxonomy_record = db_select('taxonomy_index','ti')->fields('ti')->condition('nid', $node->nid)->orderBy('tid', 'ASC')->execute();
 while($tr = $taxonomy_record->fetchAssoc()) 
 {
    $node->taxonomy[]=$tr['tid'];
 }
$query_files=db_select('file_usage','fu');
$query_files->innerJoin('file_managed', 'fm', 'fm.fid = fu.fid');
$query_files->fields('fm');
$query_files->condition('fu.id', $node->nid)->condition('fu.type', 'node');
$file_record=$query_files->execute();
 while($f = $file_record->fetchAssoc()) 
 {
 
    $node->files[$f['fid']]=$f;
 }
 #node offers
 $of_rec=db_select("advert_offers_node","aon")->fields("aon")->condition('nid',$node->nid)->execute();
 $node->advert['offers']=array();
 while($off=$of_rec->fetchObject())
  {
  $node->advert['offers'][]=$off->oid;
  }
 #$node->advert['offers']
 #node_advert_custom_fields
 $nacf_array=db_query("SELECT nacf.*,af.name as value_name,af.parent as value_parent FROM node_advert_custom_fields nacf LEFT JOIN advert_fields af ON af.id=nacf.value WHERE nacf.nid=".$node->nid);
 foreach($nacf_array as $nacf)
  {
  
  #print is_object($node->custom_fields[$nacf->field])."<hr>";
  if(isset($node->custom_fields[$nacf->field])&&is_object($node->custom_fields[$nacf->field]))
    {
    #die(isset($node->custom_fields[$nacf->field]->id)."<hr>");
     if(isset($node->custom_fields[$nacf->field]->id))
      {
      $temp_array=$node->custom_fields[$nacf->field];
      $node->custom_fields[$nacf->field]=array(0=>$temp_array);
      }
      $node->custom_fields[$nacf->field][]=$nacf;
      #}
      #pre($nacf);
    }else{
    
    $node->custom_fields[$nacf->field]=$nacf;
    }
   # pre($nacf);
  }
  
 }
 #pre($node,1);
 #pre($node->custom_fields,1);
return $node;  
}
/**
*Implementation of hook_node_form()
*/
function advert_node_form($form, &$form_state,$foo)
{
global $node;

$nid=arg(1);
if($nid!='add')
{
#
#$node=node_load(array('nid'=>$nid));
$node=node_load($nid);
$node=_advert_get_node($node);
}
#pre($node);
$form['nid']=array('#type'=>'hidden','#default_value'=>($node->nid?$node->nid:0),'#name'=>'nid','#attributes'=>array('id'=>'nid'),'#title'=>'nid');

$rec_periods=db_select('node_advert_periods','nap')->fields('nap')->orderBy('period', 'ASC')->execute();

$options_js='var field_periods= new Array;'."\n";
$period_options=array(0=>'выбрать');
  while($nap = $rec_periods->fetchAssoc()) 
    {
    $period_options[$nap['period']]=$nap['period']."дней за ".$nap['price']."гр.";
    $options_js.="field_periods['".$nap['period']."']=".$nap['price'].";\n";
    #\nperiods[".$x."]=".$nap['period'].";
 
    }
drupal_add_js("misc/advert.js");
drupal_add_css("misc/advert.css");
#drupal_add_css("misc/jquery-ui-1.9.2.custom.css");
drupal_add_css("misc/jquery-ui.css");
 $form['#tree'] = TRUE;


if(user_access('administer advert'))
{
$rec=db_select('node_advert_types','nat')->fields('nat')->orderBy('name', 'ASC')->execute();
$options_js.='var field_type_prices=new Array();'."\n";
while($tr = $rec->fetchAssoc()) 
 {
 $options[$tr['code']]=$tr['name']." (".$tr['price']." гр.)";
 $options_js.="field_type_prices['".$tr['code']."']=".$tr['price'].";\n";
 }

$form['field_type']=array('#type'=>'select',
			  '#title'=>_('Вид объявления'),
			  '#name'=>'field_type',
			  '#id'=>'field_type',
			  '#attributes'=>array('onchange'=>'check_total_price()'),
			  '#options'=>$options,
			  '#suffix'=>'<script>'.$options_js.'</script>',
			  '#default_value'=>(!empty($node->advert['field_type'])?$node->advert['field_type']:'reccomended')
			  );
}else{
$form['field_type']=array('#type'=>'hidden',
			  '#title'=>_('Вид объявления'),
			  '#name'=>'field_type',
			  '#default_value'=>(!empty($node->advert['field_type'])?$node->advert['field_type']:'reccomended'));
}			  

$rec_napt=db_select('node_advert_private_types','napt')->fields('napt')->orderBy('name', 'ASC')->execute();
$napt_jso="var napt_jso=new Array;\n";
while($napt = $rec_napt->fetchAssoc()) 
 {
 $napt_options[$napt['code']]=$napt['name']." (".$napt['price']." гр.)";
 $napt_jso.="napt_jso['".$napt['code']."']=".$napt['price'].";\n";
 } 
 
 
$form['field_private_status']=array('#type'=>'radios',
#'#options'=>array('private'=>'частное','bussiness'=>'деловое'),
'#options'=>$napt_options,
'#prefix'=>'<script>'.$napt_jso.'</script>',
'#id'=>'field_private_status',
'#attributes'=>array('onchange'=>'try_chg_advert_form();'),
'#default_value'=>(!empty($node->advert['field_private_status'])?$node->advert['field_private_status']:'private'));

#$form['action_status']=array('#type'=>'checkboxes','#options'=>array('Предлагаю','Ищу'));


### taxonomy ###

$vid=12;
$cat =  taxonomy_get_tree($vid,0,1);
#print_r($node);
$html=_draw_taxonomy_checkbox_tree($vid,$cat,$node->taxonomy);
#$dropdown_array = array('0' => '--none--');

$form['taxonomy_info']=array('#type'=>'fieldset','#title'=>'Рубрики и Города');
$form['taxonomy_info']['taxonomy1'] = array(
'#type' => 'html',
'#prefix' => $html,
);

$vid=6;
$cities =  taxonomy_get_tree($vid);
#print "<pre>";
$taxonomy2_options=array(0=>'--');
foreach($cities as $c)
  {
  $taxonomy2_options[$c->tid]=$c->name;
  //find selection for vid 6
  if(in_array($c->tid,$node->taxonomy?$node->taxonomy:array()))$taxonomy6=$c->tid;
  }  
$form['taxonomy_info']['taxonomy2']=array('#type'=>'select',
					  '#title'=>'Опубликовать в Городах',
					  '#required'=>false,'#name'=>'taxonomy[6]',
					  '#options'=>$taxonomy2_options,
					  '#default_value'=>$taxonomy6);
$tax_load='';		
if($node->taxonomy)
{
#pre($node->taxonomy);
foreach($node->taxonomy as $t)
{
if(($t)&&($t!=$taxonomy6))
  {
  #print $t;
  $tax_load.='<script>jQuery(document).ready(function () { advert_load_form('.$t.','.$nid.')});</script>';break;}
}
}
//get data for body counter
$limits=db_select('node_advert_body_chars','nadc')->fields('nadc')->orderBy('chars_max', 'ASC')->execute();
$limits_options_js='var count_limits=new Array();'."\n";
while($tr = $limits->fetchAssoc()){$limits_options_js.="count_limits[".$tr['delta']."]=".$tr['chars_max'].";\n";}

$form['field_ajax_form']=array('#type'=>'html','#prefix'=>'<div id="advert_ajax_box"></div>'.$tax_load.'<script>'.$limits_options_js.'</script>');


$form['title']=array('#type'=>'textfield',
			  '#title'=>_('Заголовок'),
#			  '#prefix'=>'<td>Что?</td><Td>',
#			  '#suffix'=>'</td></tr></table>',
			  '#default_value'=>$node->title);
		
$form['body']=array(
#'#type' => 'textarea',
'#base_type'=>'textarea',
			  '#id'=>'body',

			  '#type' => 'text_format',
#			  '#format' => 'filtered_html',
			 
			  '#required'=>true,
			  '#title'=>_('Содержание'),
			  '#default_value'=>$node->advert['body'],
			  '#attributes'=>array('onkeyup'=>'count_body_text(this.value)','id'=>'body'),
			  '#suffix'=>'<script type="text/javascript">// <![CDATA[
//инициализируем скрипт tiny_mce.js

tinyMCE.init({

mode : "textareas",
theme: "advanced",
 language : "ru",
 theme_advanced_buttons1:"bold,italic,underline,strikethrough,justifyleft,justifycenter,justifyright,justifyfull,numlist,bullist,outdent,indent",
  theme_advanced_buttons2:"",
   theme_advanced_buttons3:"",
theme_advanced_toolbar_location : "top",
        theme_advanced_toolbar_align : "left",
        theme_advanced_statusbar_location : "bottom",
        theme_advanced_resizing : true,
		  setup : function(ed) {
      ed.onKeyUp.add(function(ed, e) {
	  
	  count_body_text(strip_tags(ed.getContent()));
          //console.debug("Key up event: " + ed.getContent());
      });
   }

});

// ]]></script>
<input type="text" name=1"body_counter" id="body_counter" value="0" size="4" readonly> символов<span id="body_counter_msg"></span>
<script>'.$limits_options_js.'
count_body_text(strip_tags(document.getElementById("body").value));
</script>'
			  );	
		  
#$form['body']['format'] = filter_form(2);			  
$form['field_filter_price']=array('#type'=>'textfield',
			  '#name'=>'field_price',
			  '#prefix'=>'<div id="price_private">',
			  '#suffix'=>'</div>',
			  '#title'=>_('Цена'),
			  '#default_value'=>$node->advert['field_price'],
			  '#size'=>4);		
			  
$form['field_filter_price1']=array('#type'=>'textfield',
			  '#name'=>'field_price_one',
			  '#prefix'=>'<div id="price_bussiness">',
#			  '#suffix'=>'</div>',
			  '#title'=>_('Цена розничная'),
			  '#default_value'=>$node->advert['field_price'],
			  '#size'=>4);			  
$form['field_filter_price2']=array('#type'=>'textfield',
			  '#name'=>'field_price_optom',
			  '#default_value'=>$node->advert['field_price_optom'],
#			  '#prefix'=>'<div id="price_bussiness">',
			  '#suffix'=>'</div>',
			  '#title'=>_('Цена оптовая'),
			  '#size'=>4);		
$form['field_filter_price3']=array('#type'=>'textfield',
			  '#name'=>'field_price_from',
			  '#prefix'=>'<div id="price_buy">',
#			  '#suffix'=>'</div>',
			  '#title'=>_('Цена От'),
			  '#default_value'=>$node->advert['field_price_from'],
			  '#size'=>4);			  
$form['field_filter_price4']=array('#type'=>'textfield',
			  '#name'=>'field_price_end',
			  '#default_value'=>$node->advert['field_price_end'],
#			  '#prefix'=>'<div id="price_bussiness">',
			  '#suffix'=>'</div>',
			  '#title'=>_('Цена До'),
			  '#size'=>4);		
$form['allfiles']=array('#type'=>'fieldset');			  
$filecount =0;
// first loading
  if (!$fileslist = variable_get('advert_images', FALSE))
  {
    $fileslist =array('files'=>array(),'count'=>0);
  }
  
  // load existing list
  foreach($fileslist['files'] as $key=>$value)
  {
    // Use the #managed_file FAPI element to upload an image file.
    $form['allfiles']['file_'.$filecount] = array(
        '#title' => t('Изображение '.$filecount),
        '#type' => 'managed_file',
        '#upload_location' => 'public://advert_images/',
        '#default_value' =>$value,
        '#upload_validators' => array('file_validate_extensions' => array('gif png jpg jpeg'),'file_validate_size' => array(5*1024*1024),'file_validate_image_resolution'=>array(800*600))
    );
   
    $filecount++;
   
  }
  
  ### LOAD OLD NODE FILES ###
  if(count($foo->files))
   foreach($foo->files as $fo)
   {
   $value=$fo['fid'];
   #print $value."<hr>";
    $form['allfiles']['file_'.$filecount] = array(
        '#title' => t('Изображение '.$filecount),
        '#type' => 'managed_file',
        '#upload_location' => 'public://advert_images/',
        '#default_value' =>$value,
        '#upload_validators' => array('file_validate_extensions' => array('gif png jpg jpeg'),'file_validate_size' => array(5*1024*1024),'file_validate_image_resolution'=>array(200*150))
    );
   
    $filecount++;
   
   }

for($f=$filecount;$f<4;$f++)
{
$form['allfiles']['file_'.$f]=array('#type'=>'managed_file',
			  '#title'=>_('Изображение '.($f+1)),
			  '#progress_indicator' => "bar",
			  '#upload_location' => 'public://advert_images/',
			  '#upload_validators' => array('file_validate_extensions' => array('gif png jpg jpeg'),'file_validate_size' => array(5*1024*1024),'file_validate_image_resolution'=>array(200*150)),
);
}
 #$form['allfiles']['new']=image_field_widget_form($form,$form_state,array('field_name'=>'photo'));
$form['allfiles']['youtube']=array('#type'=>'textfield','#title'=>'Закачивайте ролики на <a href="http://www.youtube.com" target="_blank">Youtube</a> и вставте адрес (URL) в поле ниже','#description'=>'Адресс ролика на Youtube','#default_value'=>$node->advert['youtube']);
/*
$form['field_filter_type']=array('#type'=>'select',
			  '#prefix'=>'<!--table><tr><Td-->',
			  '#suffix'=>(!empty($node->field_private_status)?"<script>chg_advert_form()</script>":"").'<!--/td-->',
			  '#name'=>'field_filter_type',
			  '#id'=>'field_filter_type',
			  '#options'=>array('buy'=>'Ищу','sell'=>'Предлагаю'),
			  '#attributes'=>array('onchange'=>'chg_advert_form()'),
			  '#default_value'=>'buy');
	
*/
			  
$form['contacts']=array('#type'=>'fieldset','#title'=>'Контактные данные');
$form['contacts']['personal_name']=array('#type'=>'textfield','#title'=>'Имя','#default_value'=>$node->advert['personal_name'],'#prefix'=>'<div id="personal_name">','#suffix'=>'</div>');
$form['contacts']['bussiness_name']=array('#type'=>'textfield','#title'=>'Контактное Лицо','#default_value'=>$node->advert['bussiness_name'],'#prefix'=>'<div id="bussiness_name">','#suffix'=>'</div>');
$form['contacts']['company_name']=array('#type'=>'textfield','#title'=>'Название компании','#default_value'=>$node->advert['company_name'],'#prefix'=>'<div id="company_name">','#suffix'=>'</div>');


#$form['contacts']['phones']=array('#type'=>'fieldset','#prefix' => '<div id="names-fieldset-wrapper">','#suffix' => '</div>');



$phones=$node->custom_fields['field_phone'];
if(is_object($phones))
{
$phone0=$phones;
}else{
if($phones!=null)$phone0=array_shift($phones);
}
$form['contacts']['field_phone'][$i]=array('#type'=>'textfield',
'#name'=>'field_phone[0]',
'#class'=>'field_phone',
'#size'=>20,
'#title'=>'Телефон',
'#default_value'=>$phone0->value);
#array_shift($phones);
if(!is_object($phones)&&count($phones))
{
$phonesjs='<script>';
$i=1;
foreach($phones as $addphone)
  {
  $phonesjs.="one_more('field_phone','additional_phones');document.getElementById('field_phone[".$i."]').value='".$addphone->value."';";
  $i++;
  }
$phonesjs.='</script>';
}
 $form['contacts']['add_name'] = array(
    '#type' => 'button',
    '#value' => t('Добавить ещё один'),
    '#attributes'=>array('onclick'=>"one_more('field_phone','additional_phones');return false;"),
    '#submit' => array(''),
    '#prefix'=>'<div id="additional_phones"></div>',
    '#suffix'=>$phonesjs
    // See the examples in ajax_example.module for more details on the
    // properties of #ajax
  );
  /*
   '#ajax' => array(
          'callback' => 'ajax_check_evaopgave',
          'wrapper' => 'replace_form',names-fieldset-wrapper
          'method' => 'replace',
        )*/
        /*
  if ($form_state['num_names'] > 1) {
    $form['contacts']['phones']['remove_name'] = array(
      '#type' => 'submit',
      '#value' => t('Remove one'),
      '#submit' => array('advert_add_more_remove_one'),
      '#ajax' => array(
        'callback' => 'advert_add_more_callback',
        'wrapper' => 'names-fieldset-wrapper',
      ),
    );
  }*/
#$form['contacts']['phones']['field_phones2']=array('#type'=>'textfield','#default_value'=>(!empty($node->advert['field_phones2'])?$node->advert['field_phones2']:''));

$form['contacts']['field_address']=array('#type'=>'textfield',
			  '#title'=>_('Адрес'),
			  '#default_value'=>(!empty($node->advert['field_address'])?$node->advert['field_address']:''));
$form['contacts']['field_www']=array('#type'=>'textfield',
			  '#title'=>_('WWW'),
			  '#prefix'=>'<div id="field_www_box">',
			  '#suffix'=>'</div>',
			  '#default_value'=>(!empty($node->advert['field_www'])?$node->advert['field_www']:''));
$form['contacts']['field_email']=array('#type'=>'textfield',
			  '#title'=>_('Email'),
			  '#default_value'=>(!empty($node->advert['field_email'])?$node->advert['field_email']:''));
$form['contacts']['field_social']=array('#type'=>'textfield',
			  '#title'=>_('Соц. сети (линк)'),
			  '#default_value'=>(!empty($node->advert['field_social'])?$node->advert['field_social']:''));	
$form['contacts']['field_license']=array('#type'=>'textfield',
			  '#title'=>_('Лицензия корреспондента'),
			  '#default_value'=>(!empty($node->advert['field_license'])?$node->advert['field_license']:''));				  

			  
			  
	  

    
$form['fieldset_public_dates']=array('#type'=>'fieldset',
				     '#title'=>'Даты публикаций <span class="form-required" title="Обязательно для заполнения.">*</span>',
				      '#prefix'=>'');
#pre($node,1);
$form['fieldset_public_dates']['period']=array('#type'=>'select',
					       '#title'=>'Выбирите необходимый период',
					       '#options'=>$period_options,
					       '#id'=>'period',
					       '#prefix'=>'<table width="400" border=1><tr><td width="200">',
					       '#suffix'=>'</td><td id="period_place"></td></tr></table>
					       ',
					       '#required'=>true,
					       '#default_value'=>(isset($node)?$node->advert['period']:0),
					       '#attributes'=>array('onchange'=>'set_period(this.value);'));
					       
$form['fieldset_public_dates']['field_public_dates']['und']=array('#type'=>'html',
'#prefix'=>''._draw_public_dates($node).'<script>set_period(document.getElementById("period").value);</script>');

$form['total_price']=array('#type'=>'textfield','#title'=>'Цена за обьявление','#id'=>'total_price','#attributes'=>array('readonly'=>true),'#default_value'=>0,'#suffix'=>'<script>check_total_price();</script>');
#pre($form);
$form['status']=array('#type'=>'checkbox','#title'=>_('Опубликованно'),'#default_value'=>$node->status);



$form['submit']=array('#type'=>'submit','#value'=>'Опубликовать','#suffix'=>'<script>chg_advert_form();</script>');
if(user_access('administer advert'))
{
$form['delete']=array('#type'=>'submit','#value'=>'Удалить','#submit'=>array('_advert_delete_node',$form,$form_state));
}
#print $out;
#$form['#attributes']=array('onsubmit'=>'if(validate_advert_form())return true;else return false;');
$form['#attributes']=array('onsubmit'=>'return validate_advert_form();');
#pre($form);
return $form;
#return $form;
 #return drupal_render($form); 
}
function _advert_delete_node($form,$form_state)
{
 $inp=$form_state['input'];
 //delete node_advert
 db_delete('node_advert')->condition('nid', $nid)->execute();
 //delete node_advert_custom_fields
 db_delete('node_advert_custom_fields')->condition('nid', $nid)->execute();
 //delete node_advert_dates
 db_delete('node_advert_dates')->condition('nid', $nid)->execute();
 //delete taxonomy
 db_delete('taxonomy_index')->condition('nid', $nid)->execute();
 //delete node
 node_delete($inp);
$form_state['redirect'] = 'admin/content'; 
#die("<hr>");
}
/**
*Implementation of hook_form_submit()
*advert node control saving  
*/
function advert_node_form_submit($form, &$form_state)
{
  #pre($_POST,1);
 $arg=$form_state['build_info']['args'][0];
 $inp=$form_state['input'];
#pre($inp,1);
 if(isset($arg->nid))
  {
  $nid=$arg->nid;
  $node = node_load($nid);
  }else{
  #$inp=$arg;
 #  $inp=$form_state['input'];
$node = new stdClass();
$node->type = 'advert';
node_object_prepare($node);
  }

  #die();
$node->title = $inp['title'];
$node->field_type=Q($inp['field_type'],1);
$node->field_private_status=$inp['field_private_status'];
#$node->field_filter_type=Q($inp['field_filter_type'],1);
$node->field_price=Q((int)($inp['field_price']?$inp['field_price']:($inp['field_price_one']?$inp['field_price_one']:0)));
$node->field_price_optom=Q((int)($inp['field_price_optom']?$inp['field_price_optom']:0));
$node->field_price_from=$inp['field_price_from'];
$node->field_price_end=$inp['field_price_end'];

#$node->field_phones1=Q($inp['field_phones1'],1);
#$node->field_phones2=Q($inp['field_phones2'],1);
$node->field_address=Q($inp['contacts']['field_address'],1);
$node->field_email=Q($inp['contacts']['field_email'],1);
$node->field_www=Q($inp['contacts']['field_www'],1);
$node->field_social=Q($inp['contacts']['field_social'],1);
$node->field_license=Q($inp['contacts']['field_license'],1);
$node->period=$inp['fieldset_public_dates']['period'];
$node->total_price=$inp['total_price'];

#$node->pub_dates=$inp['field_social']
$node->language = LANGUAGE_NONE;
/*$node->body[LANGUAGE_NONE][0]['value'] = $inp['body'];
$node->body[LANGUAGE_NONE][0]['summary'] = $inp['body'];
$node->body[LANGUAGE_NONE][0]['format'] = 'filtered_html';*/
$node->uid = $arg->uid;
$node->status = (isset($inp['status'])?$inp['status']:$arg->status);
$node->promote = $arg->promote;
$node->pub_dates=$inp['pub_dates'];
$node->youtube_url=$inp['allfiles']['youtube'];
$node->personal_name=$inp['contacts']['personal_name'];
$node->bussiness_name=$inp['contacts']['bussiness_name'];
$node->company_name=$inp['contacts']['company_name'];
$node = node_submit($node); 
#pre($inp['allfiles']);

node_save($node);

$nid=$node->nid;

$data=array(
'nid' => $nid,
'body'=>$inp['body']['value'],
'field_type'=>$node->field_type,
'field_private_status'=>$node->field_private_status,
'field_price' => $node->field_price?$node->field_price:0,
'field_price_optom'=>$node->field_price_optom?$node->field_price_optom:0,
'field_price_from'=>$node->field_price_from?$node->field_price_from:0,
'field_price_end'=>$node->field_price_end?$node->field_price_end:0,
'field_address'=>$node->field_address,
'field_email'=>$node->field_email,
'field_www'=>$node->field_www,
'youtube_url'=>$node->youtube_url,
'field_social'=>$node->field_social,
'field_license'=>$node->field_license,
'period'=>$node->period,
'total_price'=>$node->total_price,
'personal_name'=>$node->personal_name,
'bussiness_name'=>$node->bussiness_name,
'company_name'=>$node->company_name);

$na=db_select("node_advert","na")->fields("na")->condition('nid',$nid)->execute()->fetchAssoc();
#pre($data);
if(isset($na['nid']))
{
try { $id = db_update('node_advert')->fields($data)->condition('nid',$nid)->execute();} catch (Exception $e) {print_r($e);}
}else{

try { $id = db_insert('node_advert')->fields($data)->execute();}catch (Exception $e) {print_r($e);}
}


#pre($inp,1);
_advert_save_offers($inp,$node);
_advert_save_custom_fields($inp,$node);
_advert_save_taxonomy($nid);

if(count($node->pub_dates))
{
db_delete('node_advert_dates')
  ->condition('nid', $nid)
  ->execute();


foreach($node->pub_dates as $d)
  {
  $d=str_replace("/","-",$d);
  $d=date('Y-m-d',strtotime($d));
  
	try {
	$data1=array('nid'=>$nid,'public_date'=>$d);
	#print_r($data1);
	$id = db_insert('node_advert_dates')->fields($data1)->execute();
	}catch (Exception $e) {
	drupal_set_message(t("Sorry, that didn't work.public_dates broken"), 'error');
	}

  }
}
## save files
#pre($form_state['values']);
#pre($node,1);
#$saved_files=_advert_save_plupload_files($form_state['values']);
$saved_files=_advert_save_managed_files($form_state['values']);

//connect fid to node

if(count($saved_files))
{
foreach($saved_files as $fid)
{
$files_data=array('fid'=>$fid,'module'=>'node','type'=>'node','id'=>$node->nid,'count'=>1);
#pre($files_data,1);
try {
  
  $id = db_insert('file_usage')->fields($files_data)->execute();
    } catch (Exception $e) {print_r($e);}
}
}
 #pre($inp,1);
#pre($saved_files,1);
#pre($inp);
#die("<hr>");
  $form_state['redirect'] = 'node/'.$nid;
}
/**
*save post taxonomy for given nid
*@param integer $nid - NID of node_advert
*@return null
*/
function _advert_save_taxonomy($nid)
{
//taxonomy
db_delete('taxonomy_index')
  ->condition('nid', $nid)
  ->execute();

if(count($_POST['taxonomy'][12]))
{
$i=0;
foreach($_POST['taxonomy'][12] as $tid=>$t)
  {
  $i++;
  $node->taxonomy[$tid]=$tid;
  try {
  $id = db_insert('taxonomy_index')->fields(array('tid'=>Q($tid),'nid'=>$nid,'created'=>time()))->execute();
    } catch (Exception $e) {print_r($e);}
  }
}
if(count($_POST['taxonomy'][6]))
{
#print $_POST['taxonomy'][6]."<hr>";
try {
  $id = db_insert('taxonomy_index')->fields(array('tid'=>Q((int)$_POST['taxonomy'][6]),'nid'=>$nid,'created'=>time()))->execute();
    } catch (Exception $e) {print_r($e);}
}
}

function _advert_save_offers($inp,$node)
{
db_delete('advert_offers_node')->condition('nid', ((int)$node->nid))->execute();
foreach($inp['offers'] as $oid=>$value)
{
if($value)
  {
  
  try { db_insert('advert_offers_node')->fields(array('nid'=>$node->nid,'oid'=>$oid))->execute();}catch (Exception $e) {print_r($e);}
  }
}

}
function _advert_save_custom_fields($inp,$node)
{

#node_advert_custom_fields
#pre($node,1);
$custom_fields=$inp['custom_fields'];
$custom_fields['field_phone']=$inp['field_phone'];

db_delete('node_advert_custom_fields')->condition('nid', ((int)$node->nid))->execute();

foreach($custom_fields as $field=>$value)
  {
  if(is_array($value))
    {
    if($field=='field_phone')
    {
     foreach($value as $k=>$v)
      {
      if(!empty($v))try { $id = db_insert('node_advert_custom_fields')->fields(array('nid'=>$node->nid,'field'=>$field,'value'=>$v))->execute();}catch (Exception $e) {print_r($e);}
      }
    }else{
    
    foreach($value as $k=>$v)
      {
     # pre(array('nid'=>$node->nid,'field'=>$field,'value'=>$k));
      if(!empty($k))try { $id = db_insert('node_advert_custom_fields')->fields(array('nid'=>$node->nid,'field'=>$field,'value'=>$k))->execute();}catch (Exception $e) {print_r($e);}
      }
      }
    }else{
    if(!empty($value))try {$id = db_insert('node_advert_custom_fields')->fields(array('nid'=>$node->nid,'field'=>$field,'value'=>$value))->execute();}catch (Exception $e) {print_r($e);}
  #  print $id."<hr>";
    }
  }
#try { $id = db_insert('node_advert')->fields($data)->execute();}catch (Exception $e) {  drupal_set_message(t("Sorry, that didn't work.node_advert_insert broken"), 'error');}

#pre($custom_fields,1);
}
function _advert_save_managed_files($input)
{
foreach($input['allfiles'] as $key=>$value) 
  {
  if(($key!='youtube')&&$value)
    {
     $file = file_load($value);
    
     #pre($file->status);
      if((isset($file))&&($file->status==0))
      {
      
        #$file->status = FILE_STATUS_PERMANENT;
      
        file_save($file);
 
        // When a module is managing a file, it must manage the usage count.
        // Here we increment the usage count with file_usage_add().
        file_usage_add($file, 'advert_images', 'sample_image', 1);
        $fids[]=$file->fid;
      }
   
    }
  }
  return $fids;
}
/*
function _advert_save_plupload_files($input)
{
#pre($input);
foreach($input as $key=>$value)
  {
  
  if(substr($key,0,5)=='file_')
    {
     $file = file_load($value);
     if($value)
     {
     #pre($file->status);
      if((isset($file))&&($file->status==0))
      {
      
        #$file->status = FILE_STATUS_PERMANENT;
      
        file_save($file);
 
        // When a module is managing a file, it must manage the usage count.
        // Here we increment the usage count with file_usage_add().
        file_usage_add($file, 'advert_images', 'sample_image', 1);
        $fids[]=$file->fid;
      }
    #print $value."<hr>";
    }
    }
  }
  return $fids;
#die("<hr>");
}*/
/*
function theme_image_multifield_multitype($variables) {
  $element = $variables['element'];

  $output = '';


  if($element['fid']['#value'] != 0) {
    // if image is uploaded show its thumbnail to the output HTML
    $output .= '<div class="multifield-thumbnail">';
    $output .= theme('image_style', array('style_name' => 'thumbnail', 'path' => file_load($element['fid']['#value'])->uri, 'getsize' => FALSE));
    $output .= drupal_render_children($element); // renders rest of the element as usual
    $output .= '</div>';
  }
return $output;
}  
function multifield_theme() {
  return array(
    'image_multifield_multitype' => array(
      'render element' => 'element',
    ),
  );
}*/

function _draw_public_dates($node)
{
global $base_url;
$pd_js='';
#pre($node);
$first=true;

if(count($node->public_dates))
{
foreach($node->public_dates as $pd)
  {
  #print $pd."<hr>";
  $pd_js.="add_public_date('".date("d/m/Y",strtotime($pd))."','reload');\n";
  if($first)
    {
    $pd_first=$pd;
    $first=false;
    }
  }

}
$html='

<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="/misc/jquery-ui.js"></script>

<table id="dates_tbl" style="display:none;"><tr><Td width="260" style="vertical-align:top;"><!--b>Выбранных дат для публикации:</b><input type="text" id="count_public_dates" value="0" readonly-->
<div id="dates_box"></div></td>
<td style="vertical-align:top;"><div id="pub_dates"></div></td></tr>

</table>';

$html.='<script>
jQuery(document).ready(function () { 
'.$pd_js.' 




var $datepicker = $("#dates_box");

$datepicker.datepicker({beforeShowDay:function(date){var id=prep_month(date.getDate())+\'/\'+prep_month(date.getMonth()+1)+\'/\'+date.getFullYear();if(document.getElementById(id)!=null){return [2,"blue"];}else if(date.toString().indexOf("Sun ")!=-1)return [1,"red"];else return [1];},
onSelect:function(date) {add_public_date(date,"new");},setDate:new Date('.date('Y',$pd_first).', '.(date('m',$pd_first)-1).', '.date('d',$pd_first).'),inline:true,dateFormat:"dd/mm/yy",firstDay:1,minDate:"-3 m",maxDate:"+3m",
monthNames:[ "Январь", "Февраль", "Март", "Апрель", "Май", "Июнь", "Июль", "Август", "Сентябрь", "Октябрь", "Ноябрь", "Декабрь" ],
dayNamesMin:[ "Вс", "Пн", "Вт", "Ср", "Чт", "Пт", "Сб" ]
});




});
</script>';
#,minDate:'.(isset($pd_first)?'new Date('.date('Y',$pd_first).', '.(date('m',$pd_first)-1).', '.date('d',$pd_first).')':'"+1d"').',
return $html;
}
function _advert_draw_week_tbl()
{
$today=time();
$output='<table border=1 id="advert_cal" cellpadding="5" cellspacing="5">
<tr><th>Пн</th><th>Вт</th><th>Ср</th><th>Чт</th><th>Пт</th><th>Сб</th><th>Вс</th></tr>'."\n";
$first=true;
$wd=1;
for($i=$today;$i<strtotime("+3 months");$i+=24*3600)
  {
  //draw empty table
  if($first)
    {
    $empty_cols=date('N',$i)-1;
    $output.='<tr>';
    for($a=0;$a<$empty_cols;$a++)
      {
      $output.='<td class="advert_accd">&nbsp;</td>';
      $wd++;
      }
     $first=false; 
    #$output.='</tr>'  
    }elseif(date('N',$i)==1){
    $output.='<tr>';
    }
  #onClick="add_public_date(\''.date('j/n/Y',$i).'\')"
  #print (date("n",$i)%2)."<hr>";
  $output.='<td id="cell'.date("j/n/Y",$i).'" title="'.date("j/n/Y",$i).'" class="advert_acca advert_cell_color'.(date("n",$i)%2).'"><span onClick="add_public_date(\''.date('j/n/Y',$i).'\')">'.date("j",$i).' '.russian_month(date("n",$i)).'</span></td>';
  if($wd==7)
    {
    $output.='</tr>'."\n";
    $wd=1;
    }else{
    $wd++;
    }
  
  }
  if($wd<8)
  {
  for(;$wd<8;$wd++)
    {
    $output.='<td class="advert_accd">&nbsp;</td>';
    }
    $output.='</tr>';
  }
 # print $wd;
$output.='</table>'."\n";
return $output;
}
/**
* Custom taxonomy form object - checkboxes tree - multy select
*@param integer $vid - vid taxonomy
*@param array $cat - result of taxonomy_get_tree func.
*@param string $title -Label (optional)
*@return string html - html of object - for injection to $form
*/
function _draw_taxonomy_checkbox_tree($vid,$cat,$parents=array(),$title='Опубликовать в Рубриках')
{
//private

if($parents==null)$parents=array();

$private_cat=taxonomy_get_tree($vid,$cat[0]->tid,1);
$html='<table width="100%"><tr><td width="300">
<h3><label>'.$title.':<span class="form-required" title="Обязательно для заполнения.">*</span></label></h3>
<div style="height:200px;overflow:auto;width:400px;">
<ul id="taxonomy_box" style="display:none;">';
foreach($private_cat as $c)
  {
  $html.=_draw_taxonomy_checkbox_tree_element($c,$vid,$parents);
  /*$html.='<li>';
  $html.='<label onClick="show_taxonomy('.$c->tid.')">'.$c->name.'</label>';
  $cat1 =  taxonomy_get_tree($vid,$c->tid,1);
  #print_r($cat1);
  if(count($cat1))
  {
  $html.='<ul id="taxo'.$c->tid.'" style="display:none;">';
  foreach($cat1 as $c1)
    {
    $html.='<li class="cb'.$c1->tid.'">';
    $html.='<label for="cb'.$c1->tid.'"><input type="checkbox" name="taxonomy['.$vid.']['.$c1->tid.']" id="cb'.$c1->tid.'"'.(in_array($c1->tid,$parents)?" checked":"").' onClick="chg_advert_taxonomy(this)"> '.$c1->name.'</label>';
    if(in_array($c1->tid,$parents))
    {
    $parent_one=$c1->tid;
    }
    $cat2 =  taxonomy_get_tree($vid,$c1->tid,1);
   if(count($cat2))
      {
      $html.='<ul>';
  foreach($cat2 as $c2)
    {
    $html.='<li class="cb'.$c2->tid.'">';
    $html.='<label for="cb'.$c2->tid.'"><input type="checkbox" name="taxonomy['.$vid.']['.$c2->tid.']" id="cb'.$c2->tid.'"'.(in_array($c1->tid,$parents)?" checked":"").' onClick="chg_advert_taxonomy(this)"> '.$c2->name.'</label>';
    #$cat2 =  taxonomy_get_tree($vid,$c1->tid,1);
    if(in_array($c2->tid,$parents))
    {
    $parent_one=$c2->tid;
    }
    $html.='</li>';
    }
  $html.='</ul>';  
  } 
    $html.='</li>';
    }
  $html.='</ul>';  
  }  
  #else $html.=_advert_taxonomy_childs($c);
  $html.='</li>';*/
  }
$html.='</ul>
<ul id="taxonomy_box1" style="display:none;">';
$bussiness_cat=taxonomy_get_tree($vid,$cat[1]->tid,1);
foreach($bussiness_cat as $c)
  {
  $html.=_draw_taxonomy_checkbox_tree_element($c,$vid,$parents);
  /*
  $html.='<li>';
  $html.='<label for="cb'.$c->tid.'"><!--input type="checkbox" name="taxonomy['.$vid.']['.$c->tid.']" id="cb'.$c->tid.'"-->'.$c->name.'</label>';
  $cat1 =  taxonomy_get_tree($vid,$c->tid,1);
  #print_r($cat1);
  if(count($cat1))
  {
  $html.='<ul>';
  foreach($cat1 as $c1)
    {
    $html.='<li class="cb'.$c1->tid.'">';
    $html.='<label for="cb'.$c1->tid.'"><input type="checkbox" name="taxonomy['.$vid.']['.$c1->tid.']" id="cb'.$c1->tid.'"'.(in_array($c1->tid,$parents)?" checked":"").' onClick="chg_advert_taxonomy(this)"> '.$c1->name.'</label>';
    if(in_array($c1->tid,$parents))
    {
    $parent_one=$c1->tid;
    }
    $cat2 =  taxonomy_get_tree($vid,$c1->tid,1);
   if(count($cat2))
      {
      $html.='<ul>';
  foreach($cat2 as $c2)
    {
    $html.='<li class="cb'.$c2->tid.'">';
    $html.='<label for="cb'.$c2->tid.'" ><input type="checkbox" name="taxonomy['.$vid.']['.$c2->tid.']" id="cb'.$c2->tid.'"'.(in_array($c1->tid,$parents)?" checked":"").' onClick="chg_advert_taxonomy(this)"> '.$c2->name.'</label>';
    #$cat2 =  taxonomy_get_tree($vid,$c1->tid,1);
    if(in_array($c2->tid,$parents))
    {
    $parent_one=$c2->tid;
    }
    $html.='</li>';
    }
  $html.='</ul>';  
  } 
    $html.='</li>';
    }
  $html.='</ul>';  
  }  
  #else $html.=_advert_taxonomy_childs($c);
  $html.='</li>';*/
 
  }
$html.='</ul>
</div></td><td style="vertical-align:top;"><label>Выбранные рубрики для публикации</label><div class="msg_place"></div>
<ul id="loaded_taxonomy"></ul></td></tr></table>';
if($parent_one)
{
#$html.='<script>advert_load_form('.$parent_one.',nid)</script>';
}
if($parents)
{
$html_parent='';
foreach($parents as $parent)
  {
  $term=taxonomy_term_load($parent);
  
  if($term->vid){$parent_tid=$term->tid;$html_parent.='<script>if(document.getElementById("cb'.$parent.'"))chg_advert_taxonomy(document.getElementById("cb'.$parent.'"))</script>'."\n";}
  }
  $ded=array_shift(taxonomy_get_parents($parent_tid));
  
if($ded->tid)$html.='<script>show_taxonomy('.$ded->tid.');</script>';
$html.=$html_parent;
}
return $html;
}
function _draw_taxonomy_checkbox_tree_element($c,$vid,$parents)
{
 $html='<li>';
  $html.='<label onClick="show_taxonomy('.$c->tid.')">'.$c->name.'</label>';
  $cat1 =  taxonomy_get_tree($vid,$c->tid,1);
  #print_r($cat1);
  if(count($cat1))
  {
  $html.='<ul id="taxo'.$c->tid.'" style="display:none;">';
  foreach($cat1 as $c1)
    {
    $html.='<li class="cb'.$c1->tid.'">';
    $html.='<label for="cb'.$c1->tid.'"><input type="checkbox" name="taxonomy['.$vid.']['.$c1->tid.']" id="cb'.$c1->tid.'"'.(in_array($c1->tid,$parents)?" checked":"").' onClick="chg_advert_taxonomy(this)"> '.$c1->name.'</label>';
    if(in_array($c1->tid,$parents))
    {
    $parent_one=$c1->tid;
    }
    $cat2 =  taxonomy_get_tree($vid,$c1->tid,1);
   if(count($cat2))
      {
      $html.='<ul>';
  foreach($cat2 as $c2)
    {
    $html.='<li class="cb'.$c2->tid.'">';
    $html.='<label for="cb'.$c2->tid.'"><input type="checkbox" name="taxonomy['.$vid.']['.$c2->tid.']" id="cb'.$c2->tid.'"'.(in_array($c1->tid,$parents)?" checked":"").' onClick="chg_advert_taxonomy(this)"> '.$c2->name.'</label>';
    #$cat2 =  taxonomy_get_tree($vid,$c1->tid,1);
    if(in_array($c2->tid,$parents))
    {
    $parent_one=$c2->tid;
    }
    $html.='</li>';
    }
  $html.='</ul>';  
  } 
    $html.='</li>';
    }
  $html.='</ul>';  
  }  
  #else $html.=_advert_taxonomy_childs($c);
  $html.='</li>';
  return $html;
}
/**
*AJAX draw addinional part of advert_node_form
*Look /misc/advert.js function advert_load_form()
**/ 
function advert_additional_form($tid,$nid)
{
if($nid)
{
$node=node_load($nid);
#$node=(object)array('nid'=>$nid);
$node=_advert_get_node($node);
#pre($node);
$custom_fields=$node->custom_fields;
#pre($custom_fields);
}
$tids=explode(",",$tid);
#pre($tids);
$form['special_fields']=array('#type'=>'fieldset');
$re=db_select('node_advert_terms_taxonomy','natt');
$re->innerJoin('node_advert_terms','nat','nat.id=natt.node_advert_terms_id');
$re->innerJoin('advert_fields_type','aft','aft.type=nat.code');
$re->fields('aft')->condition('natt.tid', $tids,'IN');
$re->orderBy('aft.weight');

$rec=$re->execute();
$form['special_fields']['offers']=_advert_offer_checkboxes($tids,$node);
while($advert_type=$rec->fetchAssoc())
{
#pre($advert_type['field']."|".$advert_type['form_type']);
  #switch($advert_type['form_type'])
  #{
  #case 'select':
  if($advert_type['field']=='car_brand')
  {
  $form['special_fields'][$advert_type['field']]=_advert_create_fields_aj(array($advert_type['name'],'Модель'),$advert_type['field'],$custom_fields);
  
  //is car
  #$car_brand=$advert_type['value'];
  #$js_load='<script>advert_load_car_model()</script>';
  
  }else{
   $form['special_fields'][$advert_type['field']]=_advert_create_fields($advert_type['name'],$advert_type['field'],$custom_fields,$node);
  }
  #break;
  #case 'checkboxes':
  #$form['special_fields'][$advert_type['field']]=_advert_create_fields_checkboxes(null,$advert_type['field'],$custom_fields);
  #break;
  #}
}

  print drupal_render($form);
die("<hr>");
}
function advert_chk_date()
{
 #header ("content-type: text/xml");
 $nid=Q($_POST['nid'],1);
 
 $tids=explode(",",Q($_POST['tids'],1));
 $d=str_replace("/","-",$_POST['d']);
 $d=strtotime($d);
 if($nid)
 {
 for($i=0;$i<count($tids);$i++)
  if(empty($tids[$i]))unset($tids[$i]);

$sql="SELECT DISTINCT n.nid 
FROM `node` n
LEFT JOIN node_advert na ON na.nid=n.nid
LEFT JOIN node_advert_dates nad ON nad.nid=n.nid
LEFT JOIN taxonomy_index ti ON ti.nid=n.nid
WHERE n.type='advert' AND n.status=1 AND na.field_type='reccomended' AND nad.public_date='".Q(date('Y-m-d',$d),1)."' AND ti.tid IN (".implode(",",$tids).") and n.nid!=".Q((int)$nid);
#print $sql;
$record=db_query($sql);


 while($f = $record->fetchAssoc()) 
 {
 $data[]=$f['nid'];
 }

if(count($data)>4)$result=0;
else $result=1;

die('<div>'.$result.'</div>');
}
return false;
}
/**
*AJAX Car model loading via car brand name
*loaded from /misc/advert.js advert_load_car_model()
**/ 
function advert_car_model($name,$parent=false)
{
$ar=explode("|",$name);
$id=$ar[0];
$title=$ar[1];
$query_files=db_select('advert_fields','af');
$query_files->innerJoin('advert_fields', 'af1', 'af1.parent = af.id');
$query_files->fields('af1');
$query_files->condition('af.id', $id);
$file_record=$query_files->execute();

while($r=$file_record->fetchAssoc())
  {
  $opt[]=$r;
  }
  $out="<label>".$title."</label><select name='custom_fields[car_model]' class='form-select' >";
  foreach($opt as $op)
    {
    $out.="<option value='".$op['id']."' ".(($parent==$op['id'])?" selected":"").">".$op['name']."</option>\n";
    }
  $out.="</select>";
  if(!$parent)die($out);
  else return $out;
}
/**
*Draw form ajax element for car_brand
*called from advert_additional_form
*/
function _advert_create_fields_aj($titles,$field,$custom_fields)
{
$default=$custom_fields[$field];
#pre($default);
$fields_rec=db_select('advert_fields','af')->fields('af')->condition('field',$field)->condition('parent',0)->orderBy('id', 'ASC')->execute();
$opt=array(0=>'-выбрать-');
while($r=$fields_rec->fetchAssoc())
  {
  $opt[$r['id']]=$r['name'];
  }
  #pre($default);
if($default->value)
{
//load default_car_model
#db_select('')
}
return array('#type'=>'select','#title'=>$titles[0],'#name'=>'custom_fields['.$field.']','#options'=>$opt,'#attributes'=>array('onchange'=>'advert_load_car_model(this.value,"'.$titles[1].'");'),
'#suffix'=>'<div id="car_models_box">'.($default->value?advert_car_model($default->value."|".$titles[1],$custom_fields['car_model']->value):'').'</div>','#value'=>$default->value);

}
/**
*Draw form select element
*called from advert_additional_form
*/
function _advert_create_fields($title,$field,$custom_fields,$node)
{
#$field=$custom_fields[$titles[0]];
#print $default['value']."<hr>";
$default=$custom_fields[$field];

$fields_rec=db_select('advert_fields','af')->fields('af')->condition('field',$field)->orderBy('id', 'ASC')->execute();
#$fields_rec=db_query('advert_fields','af')->fields('af')->condition('field',$field)->orderBy('id', 'ASC')->execute();
$opt=array(0=>'-выбрать-');

while($r=$fields_rec->fetchAssoc())
  {
  $opt[$r['id']]=$r['name'];
  }
  #pre($default);
  $def=db_select('advert_fields','af')->fields('af')->condition('field',$field)->condition('id',$default->value)->execute()->fetchObject();
#  pre($def);
return array('#type'=>'select','#title'=>$title,'#name'=>'custom_fields['.$field.']','#options'=>$opt,'#value'=>$def->id);

}
/**
*Draw form checkboxes element
*called from advert_additional_form
*/
function _advert_offer_checkboxes($tids,$node)
{

$sql="SELECT DISTINCT ao.*
FROM `node_advert_terms_taxonomy` natt 
LEFT JOIN node_advert_terms nat ON nat.id=natt.node_advert_terms_id 
INNER JOIN advert_offers_code aoc ON aoc.code=nat.code
LEFT JOIN advert_offers ao ON ao.id=aoc.oid
WHERE natt.tid IN (".Q(implode(",",$tids),1).")";
#print $sql;
$fields_rec=db_query($sql);

$form['field_type_chkb']['tblbefore']=array('#type'=>'html','#prefix'=>'<table style="width:500px;"><tr>');
$i=0;
while($r=$fields_rec->fetchAssoc())
  {
  $form['field_type_chkb'][$r['id']]=array('#type'=>'checkbox','#title'=>$r['name'],'#prefix'=>'<td>','#suffix'=>'</td>','#value'=>$r['id'],'#checked'=>((in_array($r['id'],$node->advert['offers']))?true:false),'#name'=>'offers['.$r['id'].']');
  #$opt[$r['name']]=$r['name'];
  $i++;
  }
$form['field_type_chkb']['tblafter']=array('#type'=>'html','#suffix'=>'</tr></table>');
 return $form; 
#return array('#type'=>$type,'#title'=>$title,'#name'=>$field,'#options'=>$opt);

}
?>